package app.auto.designer.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;

import android.widget.ListView;

import org.json.JSONObject;

import java.util.Arrays;
import java.util.List;

import app.auto.designer.R;
import app.auto.designer.ActivityBase;
import app.auto.designer.func.FuncListActivity;
import app.auto.runner.base.RRes;
import app.auto.runner.base.action.ViewInflater;
import app.auto.runner.base.intf.FunCallback;
import app.auto.runner.base.widget.ImageView;
import app.auto.runner.base.DialogUtil;
import app.auto.runner.base.MapViewConf;

public class EditActivity extends ActivityBase {

    public List<View> sibling = new ArrayList<View>();
    public View focused;
    public ViewGroup focusedGroup;
    public View topview;

    public ViewGroup getTopview() {
        return (ViewGroup) topview;
    }

    private ListView listview;
    private List list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.auto_edit);
        setFocused(topview = getGroup(R.id.bench).getChildAt(0));
        setGroupFocused((ViewGroup) topview);
        getView(R.id.addope).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getTopview().addView(new LinearLayout(v.getContext()));
            }
        });
        getView(R.id.addope).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getTopview().addView(new LinearLayout(v.getContext()));
            }
        });


        getView(R.id.up).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (focused.getParent() == null || focused.getParent() != getTopview()) {

                } else {
                    setFocused((ViewGroup) focused.getParent());
                }
            }
        });
        getView(R.id.left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (focused.getParent() == null) {

                } else {
                    ViewGroup vg = (ViewGroup) focused.getParent();
                    int i = vg.indexOfChild(focused);
                    if (i == 0) {

                    } else {
                        setFocused(vg.getChildAt(i - 1));
                    }
                }
            }
        });

        getView(R.id.right).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (focused.getParent() == null) {

                } else {
                    ViewGroup vg = (ViewGroup) focused.getParent();
                    int i = vg.indexOfChild(focused);
                    if (i == vg.getChildCount() - 1) {

                    } else {
                        setFocused(vg.getChildAt(i + 1));
                    }
                }
            }
        });

        getView(R.id.down).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (!(focused instanceof ViewGroup) || ((ViewGroup) focused).getChildCount() == 0) {

                    } else {
                        setFocused(((ViewGroup) focused).getChildAt(0));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        getView(R.id.nav).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {

                    int idx = tiviews.indexOf(focused);
                    if (idx == tiviews.size() - 1) {
                        idx = 0;
                    } else {
                        idx++;
                    }
                    setFocused(tiviews.get(idx));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        getView(R.id.navgrp).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {

                    int idx = grviews.indexOf(focusedGroup);
                    if (idx == grviews.size() - 1) {
                        idx = 0;
                    } else {
                        idx++;
                    }
                    setGroupFocused(grviews.get(idx));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        getView(R.id.navpre).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {

                    int idx = tiviews.indexOf(focused);
                    if (idx == 0) {
                        idx = tiviews.size() - 1;
                    } else {
                        idx--;
                    }
                    setFocused(tiviews.get(idx));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        getView(R.id.addview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ListView listView = new ListView(v.getContext());
                listView.setTag("fake:[[LinearLayout],[RelativeLayout],[TextView],[ImageView],[Button],[CheckBox],[RadioButton]]");
                ViewInflater.tagrate(listView);
                listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        String text = (String) ((TextView)view).getText();
                        String name = "android.widget."+text;
                        JSONObject jo = new JSONObject();
//                        jo.put("")
                    }
                });
//                new AlertDialog.Builder(v.getContext()).setView(listView)
            }
        });
        getView(R.id.add).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {

                    int idx = tiviews.indexOf(focused);
                    if (idx == 0) {
                        idx = tiviews.size() - 1;
                    } else {
                        idx--;
                    }
                    setFocused(tiviews.get(idx));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        visvitViews(getTopview(), false);
    }

    @SuppressLint("NewApi")
    public void setGroupFocused(ViewGroup viewgroup) {
        if (this.focusedGroup != null) {
            this.focusedGroup.setForeground(new ColorDrawable(0x00000000));

        }
        this.focusedGroup = viewgroup;
        viewgroup.setForeground(getResources().getDrawable(R.drawable.auto_background_rect_yellow, null));
    }

    List<View> tiviews = new ArrayList<View>();
    List<ViewGroup> grviews = new ArrayList<ViewGroup>();

    //设置有id的控件 带白框
    private void visvitViews(View userview, boolean selfimposed) {
        if (userview.getId() != 0) {

//            if (selfimposed) {
//                setViewClickPanel(userview);
//            }
        }
        if (userview instanceof TextView) {
            TextView tv = (TextView) userview;

            if (!TextUtils.isEmpty(tv.getText()) || !TextUtils.isEmpty(tv.getHint())) {
                setViewClickPanel(userview);
            }
        } else if (userview instanceof ImageView) {
            ImageView tv = (ImageView) userview;

            if (!TextUtils.isEmpty(tv.getUrl())) {
                setViewClickPanel(userview);
            }
        }
        if (userview instanceof ViewGroup) {
            grviews.add((ViewGroup) userview);
            for (int i = 0; i < ((ViewGroup) userview).getChildCount(); i++) {
                View view = ((ViewGroup) userview).getChildAt(i);

                visvitViews(view, true);
            }

        }
    }

    private void setViewClickPanel(final View userview) {
        tiviews.add(userview);
        if (userview instanceof AdapterView) {

        } else {
            userview.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View v) {
                    String value = "";
                    if (v instanceof TextView) {
                        value = ((TextView) v).getText().toString();
                    } else if (v instanceof app.auto.runner.base.widget.ImageView) {
                        value = ((app.auto.runner.base.widget.ImageView) v).getUrl();
                    }
                    String id = RRes.getAttrValue_itsname().get(v.getId());
                    setFocused(userview);
                    doubleClick_2(new FunCallback() {
                        @Override
                        public void simpleRun(Object aty) {
                            startActivity(new Intent(v.getContext(), FuncListActivity.class));
                        }
                    });
                }
            });
        }
    }


    @SuppressLint("NewApi")
    public void setFocused(View focused) {
        if (this.focused != null) {
            this.focused.setForeground(new ColorDrawable(0x00000000));
//            ((View) this.focused.getParent()).setForeground(new ColorDrawable(0x00000000));

        }
        this.focused = focused;
        status(getTextView(R.id.status), focused);
    }

    private long[] mHits = new long[2];

    private void doubleClick_2(FunCallback cb) {
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();//获取手机开机时间
        if (mHits[mHits.length - 1] - mHits[0] < 500) {
            /**双击的业务逻辑*/
            cb.simpleRun(null);
        }
    }

    @SuppressLint("NewApi")
    private void status(TextView status, View focused) {
        //处理标题
        String idx = "";
        String id = "";
        String childrencount = "";
        if (focused.getParent() != null) {
            idx = "[ " + (((ViewGroup) focused.getParent()).indexOfChild(focused) + 1) + "/" + ((ViewGroup) focused.getParent()).getChildCount() + " ]";
        }
        if (focused instanceof ViewGroup) {
            childrencount = " : " + ((ViewGroup) focused).getChildCount() + "";
        }

        if (focused.getId() > 0) {
            String v = RRes.getAttrValue_itsname().get(focused.getId());
            if (v != null) {
                id = v;
            }

        }
        id = id.equals("") ? "" : "   " + id + "  ";
        String name = focused.getClass().getSimpleName().replace("VIEW", "View").replace("LAYOUT", "Layout");
        String result = idx + " : " + name + id + childrencount;
        status.setText(result);
        focused.setForeground(getResources().getDrawable(R.drawable.auto_background_rect_white, null));
//        ((View) focused.getParent()).setForeground(getResources().getDrawable(R.drawable.auto_background_rect_yellow, null));
        click(R.id.save_back, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogUtil.DialogInfo du = new DialogUtil.DialogInfo(view.getContext());
                du.aty = view.getContext();
                du.view = listview = new ListView(view.getContext());
                MapViewConf.with(view.getContext()).source(list = Arrays.asList(new String[]{"线性布局", "相对布局"}), listview).conf(MapViewConf.with(view.getContext()).source(R.layout.auto_string_item)).toView();
                du.neutralButtonClickListener = new DialogUtil.DialogClicker();
                DialogUtil.showNeutralDialog(du, true);
                listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        switch (list.indexOf(adapterView.getItemAtPosition(i).toString())) {
                            case 0:
                                break;
                            case 1:
                                break;
                        }

                    }
                });

            }
        });
    }
}
